<?php
namespace app\controller\handler;
use think\Db;

class Login{

  //处理登录
  public function doLogin(){
    $base = input('post.')['base'];
    $user = isset($base['user']) ? trim($base['user']): '';
    $password = isset($base['password']) ? trim($base['password']): '';
    $flag = true;
    if(!$user || !$password){
      $flag = false;
      $result['ret'] = 0;
      $result['msg'] = '确保内容填写完整';
    }

    if($flag){
      $sql = "select u.*, prp.power_ids
              from `#__user` u
              left join `#__project_role_power` prp on prp.role_id=u.role_id and prp.status=1
              where u.status = 1 and (email=? or mobile=?)
            ";
      $res = Db::query($sql,[$user,$user]);
      if($res && count($res)>0){
        if(base_encode($password) == $res[0]['password']){
          unset($res[0]['password']);
          $this->storeUserInfo($res[0]['id'],$res[0],time());
          $result['ret'] = 1;
          $result['type'] = $res[0]['type'];
          $result['msg'] = '登陆成功';
        }else{
          $resilt['ret'] = 0;
          $result['msg'] = '帐号或密码错误';
        }
      }else{
        $result['ret'] = 0;
        $result['msg'] = '帐号不存在';
      }
    }
    return $result;
  }

  //存储用户信息
  public static function storeUserInfo($userID,$userInfo,$refreshTime){
    //patch：根据role_id获取权限arr
    if($userInfo['role_id'] != 0){
      $power_ids = $userInfo['power_ids'];
      $power_idsArr = explode(',',$power_ids);
      $sql = 'select * from `#__power` where status=?';
      $powerAll = Db::query($sql,[1]);
      foreach($power_idsArr as $key=>$value){
        foreach($powerAll as $k=>$val){
          if($value == $val['id']){
            $userInfo['permission'][] = $val['value'];
          }
        }
      }
    }
    //end
    session('userInfo',$userInfo);
    session('userID',md5($userID));
    session('refreshTime',$refreshTime);
  }

  //处理注销
  public function doLogout(){
    session(null);
    $userID = session('?userID') ? session('userID') : '';
    if($userID){
      $result['ret'] = 0;
      $result['msg'] = '注销失败';
    }else{
      $result['ret'] = 1;
      $result['msg'] = '注销成功';
    }
    return $result;
  }


}//END